package cn.wolfcode.luowowo.service.impl;


import cn.wolfcode.luowowo.domain.Region;
import cn.wolfcode.luowowo.query.RegionQuery;
import cn.wolfcode.luowowo.repository.RegionRepository;
import cn.wolfcode.luowowo.service.IRegionService;
import cn.wolfcode.luowowo.util.DBHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;


@Service
public class RegionServiceImpl implements IRegionService {



    @Autowired
    private RegionRepository regionRepository;

    @Autowired
    private MongoTemplate template;


    @Override
    public Region get(String id) {
        return regionRepository.findById(id).orElse(null);
    }

    @Override
    public List<Region> list() {
        return regionRepository.findAll();
    }

    @Override
    public void save(Region region) {
        regionRepository.save(region);
    }

    @Override
    public void update(Region region) {
        regionRepository.save(region);
    }

    @Override
    public void delete(String id) {
        regionRepository.deleteById(id);
    }

    @Override
    public Page<Region> query(RegionQuery qo) {

        Query query = new Query();

        PageRequest pageable = PageRequest.of(qo.getCurrentPage()-1, qo.getPageSize(), Sort.Direction.DESC, "_id");

        return DBHelper.query(template,Region.class,query,pageable);
    }

    @Override
    public void saveOrUpdate(Region region) {

        if(StringUtils.hasLength(region.getId())){
            this.update(region);
        }else{
            this.save(region);
        }
    }

    @Override
    public void changeHotValue(String id, int hot) {
        Region region = this.get(id);
        region.setIshot(hot);
        this.update(region);
    }

    @Override
    public List<Region> findByIshotOrderBySequenceAsc(int stateHot) {
        return regionRepository.findByIshotOrderBySequenceAsc(stateHot);

    }


}
